﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		CompressionFilter.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 // 
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.IO.Compression;
using System.Security.Permissions;
using System.Web;
using System.Web.Mvc;
using Dexter.Services;

namespace Dexter.Web.Mvc.Filters {
	[AttributeUsage ( AttributeTargets.Class | AttributeTargets.Method , Inherited = true , AllowMultiple = false )]
	[AspNetHostingPermission ( SecurityAction.Demand , Level = AspNetHostingPermissionLevel.Minimal )]
	public class CompressionFilter : ActionFilterAttribute {
		readonly IConfigurationService configurationService;

		/// <summary>
		/// Initializes a new instance of the <see cref="T:System.Web.Mvc.ActionFilterAttribute"/> class.
		/// </summary>
		public CompressionFilter ( IConfigurationService configurationService ) {
			this.configurationService = configurationService;
		}

		/// <summary>
		/// 	Called by the MVC framework before the action method executes.
		/// </summary>
		/// <param name = "filterContext">The filter context.</param>
		public override void OnActionExecuting ( ActionExecutingContext filterContext ) {
			base.OnActionExecuting ( filterContext );

			var siteConfiguration = configurationService.Configuration;

			if ( !siteConfiguration.AdvancedFeatues.DataCompression ) {
				return;
			}

			HttpRequestBase request = filterContext.HttpContext.Request;

			string acceptEncoding = request.Headers[ "Accept-Encoding" ];

			if ( string.IsNullOrEmpty ( acceptEncoding ) ) {
				return;
			}

			acceptEncoding = acceptEncoding.ToUpperInvariant ( );

			HttpResponseBase response = filterContext.HttpContext.Response;

			if ( acceptEncoding.Contains ( "GZIP" ) ) {
				response.AppendHeader ( "Content-encoding" , "gzip" );
				response.Filter = new GZipStream ( response.Filter , CompressionMode.Compress );
			}
			else if ( acceptEncoding.Contains ( "DEFLATE" ) ) {
				response.AppendHeader ( "Content-encoding" , "deflate" );
				response.Filter = new DeflateStream ( response.Filter , CompressionMode.Compress );
			}
		}
	}
}
